/**
 * @description 拉取抓怕记录
 * @author cx
 * @date 2024.06.07 14:41
 */


package com.cx.service.yitu.serviceimp;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.cx.entity.PushedData;
import com.cx.entity.RestResp;
import com.cx.service.PushedDataService;
import com.cx.service.yitu.RetrofitService;
import com.cx.service.yitu.service.YiTuService;
import com.cx.utils.FileToBase64;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class PullBoxRecord {

    @Autowired
    private PushedDataService pushedDataService;

    @Autowired
    private RetrofitService retrofitService;


    @Value("${imagePath.path}")
    private String imageUrl;


    /*description   依图老版本盒子推图 http://172.16.30.160:8089/boxPushRecord
     *以参数的方式进行传递， params 表示推送过来的数据
     * */
    public void pullRecord(Map<String, Object> params) {

        // 获取相似的人脸
        List<Map<String, Object>> retrieval_results = (List<Map<String, Object>>) params.get("retrieval_results");
        Map<String, Object> simPerson = retrieval_results.get(0);
        List<Map<String, Object>> simFace = (List<Map<String, Object>>) simPerson.get("similar_faces");
         //CollectionUtils.isEmpty(simFace)
        //JSONObject.parseArray(JSON.toJSONString(params.get("retrieval_results"))).getJSONObject(0).getJSONArray("similar_faces").size() != 0
        //有比对然后进来
        if (JSONObject.parseArray(JSON.toJSONString(params.get("retrieval_results"))).getJSONObject(0).getJSONArray("similar_faces").size() != 0) {
            System.out.println("有没有进来");
            try {
                PushedData data = new PushedData();
//                System.out.println(params);
                //人像库id
                String portraitLibrary = JSONObject.parseArray(JSON.toJSONString(params.get("retrieval_results"))).getJSONObject(0).getString("repo_id");
                System.out.println("人像库id的值为" + portraitLibrary);

                YiTuService apiByIPService = retrofitService.getApiByIPService(YiTuService.class);
                JSONObject imageExecute = apiByIPService.getImageLibrary(portraitLibrary).execute().body();
                System.out.println(imageExecute);
                //人像库名称
                data.setReserved2(imageExecute.getString("name"));

                JSONObject extra_meta = JSONObject.parseArray(JSON.toJSONString(params.get("retrieval_results")))
                        .getJSONObject(0)
                        .getJSONArray("similar_faces")
                        .getJSONObject(0)
                        .getJSONObject("extra_meta");

                //名称
                data.setReserved(extra_meta.getString("name"));

                //接口接收图片并将路径存入数据库
                String filePath = imageUrl + "db" + extra_meta.getString("db_image_url") + ".jpg";

                //图片路径
                data.setReserved3(filePath);
                FileOutputStream fos = new FileOutputStream(filePath);
                InputStream in = apiByIPService.downloadPicWithUrl(extra_meta.getString("db_image_url")).execute().body().byteStream();
                int count = 0;
                byte[] buffer = new byte[1024];
                while ((count = in.read(buffer)) != -1) {
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                in.close();


                //摄像头名称
                data.setChannelName(JSON.toJSONString(params.get("channel_name")));

                //捕获状态
                data.setTrackStatus(JSON.toJSONString(params.get("track_status")));

                //此track人脸质量分数
                data.setFaceQuality(params.get("face_quality").toString());

                //时间
                String dateString = params.get("iso8601timestamp").toString();
                OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateString, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
                Date date = Date.from(offsetDateTime.toInstant());
                data.setIso8601timestamp(date);

                //人脸图Base64
                String faceContent = JSONObject.parseObject(JSONObject.toJSONString(params.get("face_image"))).getString("content");
                String FaceImage = imageUrl + "face" + new Date().getTime() + ".jpg";
                data.setFaceImage(FaceImage);
                FileToBase64.decoderBase64File(faceContent, FaceImage);

                //场景图Base64
                String content = JSONObject.parseObject(JSONObject.toJSONString(params.get("scene_image"))).getString("content");
                //场景图片
                String imageNam = imageUrl + "scene" + new Date().getTime() + ".jpg";
                data.setSceneImage(imageNam);
                FileToBase64.decoderBase64File(content, imageNam);


                pushedDataService.insertSelective(data);

            } catch (Exception e) {
                log.error("Exception=========" + e);
            }
            log.info("拉取抓拍成功");
        }

    }

}
